import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Response, Request } from 'express';

@Catch(HttpException) // 监听 状态吗错误
export class MyExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    // 指定传输协议
    const ctx = host.switchToHttp();
    // 获取响应对象(注意这里的Response是express的Response)
    const response = ctx.getResponse<Response>();
    // 获取请求对象(注意这里的Request是express的Request)
    const request = ctx.getRequest<Request>();
    // 获取状态码
    const status = exception.getStatus();
    // 获取异常信息
    const message = exception.message;

    let resMessage: string | Record<string, any> = exception.getResponse();

    console.log('---MyExceptionFilter---');

    if (typeof resMessage === 'object') {
      resMessage = resMessage.message;
    }

    // 统一组装返回的数据格式
    response.status(status).json({
      statusCode: status,
      message: resMessage || message,
      path: request.url,
      success: false,
    });
  }
}
